<?php

namespace backend\controllers;

use common\core\ZController;
use common\models\Division;
use Yii;
use app\models\Contactor;
use yii\bootstrap\Html;
use yii\data\ActiveDataProvider;
use yii\web\BadRequestHttpException;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * ContactorController implements the CRUD actions for Contactor model.
 */
class ContactorController extends ZController
{
    public $enableCsrfValidation = false;
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }

    /**
     * Lists all Contactor models.
     * @return mixed
     */
    public function actionIndex()
    {
        $keyword = Html::encode(Yii::$app->request->get('keyword'));
        $query = Contactor::find();
//        var_dump(Yii::$app->request->get('keyword'));die;
        if($keyword && $keyword != ''){
            $query->andFilterWhere(['like', 'name', $keyword])
                ->orFilterWhere(['like' , 'mobile' ,$keyword])
                ->orFilterWhere(['like' , 'company_name' , $keyword]);
        }
//        var_dump($query->createCommand()->sql);die;

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        return $this->render('index', [
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Contactor model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Contactor model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Contactor();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing Contactor model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing Contactor model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the Contactor model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Contactor the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Contactor::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

    public function actionSetHot()
    {
        $cid = intval(Yii::$app->request->get('cid'));
        if(!$cid){
            throw new BadRequestHttpException('请求参数错误');
        }

        $contactorModel = $this->findModel($cid);

        $contactorModel->is_hot = 1;
        if(!$contactorModel->save(false)){
            Yii::$app->session->setFlash('error' , '设置失败，请稍后再试!');
        }
        Yii::$app->session->setFlash('success' , '设置成功!');
        $this->redirect(['/contactor/index']);

    }
    public function actionCancelHot()
    {
        $cid = intval(Yii::$app->request->get('cid'));
        if(!$cid){
            throw new BadRequestHttpException('请求参数错误');
        }

        $contactorModel = $this->findModel($cid);

        $contactorModel->is_hot = 0;
        if(!$contactorModel->save(false)){
            Yii::$app->session->setFlash('error' , '取消失败，请稍后再试!');
        }
        Yii::$app->session->setFlash('success' , '取消成功!');
        $this->redirect(['/contactor/index']);

    }

    public function actionExport()
    {
        $excel = new \PHPExcel();
        $data = Contactor::find()->all();


        $row = 1;//行从1开始
        foreach($data as $value){
            $colum = 0;//列从0开始
            $excel->setActiveSheetIndex(0)->setCellValueByColumnAndRow($colum , $row ,$value['name']);
            $colum++;
            $excel->setActiveSheetIndex(0)->setCellValueByColumnAndRow($colum , $row ,$value['company_name']);
            $colum++;
            $excel->setActiveSheetIndex(0)->setCellValueByColumnAndRow($colum , $row ,$value['position']);
            $colum++;
            $excel->setActiveSheetIndex(0)->setCellValueByColumnAndRow($colum , $row ,$value['mobile']);
            $colum++;
            $excel->setActiveSheetIndex(0)->setCellValueByColumnAndRow($colum , $row ,$value['web_site']);
            $colum++;
            $excel->setActiveSheetIndex(0)->setCellValueByColumnAndRow($colum , $row ,Division::getCitynameById($value['city_id']));
            $colum++;
            $excel->setActiveSheetIndex(0)->setCellValueByColumnAndRow($colum , $row ,date('Y-m-d H:i:s' , $value['create_time']));
            $colum++;
            $row++;
        }

        // Redirect output to a client’s web browser (Excel2007)
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="'.date("Y-m-d").'.xls"');
        header('Cache-Control: max-age=0');
// If you're serving to IE 9, then the following may be needed
        header('Cache-Control: max-age=1');
        $objWriter = \PHPExcel_IOFactory::createWriter($excel, 'Excel5');
        $objWriter->save('php://output');





    }
}
